package com.huahua.api.util;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.text.StrJoiner;
import cn.hutool.core.util.StrUtil;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbMakerConfigException;
import org.lionsoul.ip2region.DbSearcher;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @program: base-service
 * @description:
 * @author: hui.zhang
 * @date: 2021/8/26 5:18 下午
 **/
public class IPUtil {

    private static final String file = "ip2region.db";
    private static DbSearcher dbSearcher = null;

    static {
        ClassPathResource classPathResource = new ClassPathResource(file);
        InputStream inputStream = null;
        try {
            inputStream = classPathResource.getInputStream();
            DbConfig config = new DbConfig();
            dbSearcher = new DbSearcher(config, IoUtil.readBytes(inputStream, true));
        } catch (IOException | DbMakerConfigException e) {
            e.printStackTrace();
        }
        System.out.println("初始化完成");

    }

    /**
     * 根据ip获取地址信息
     *
     * @param ip 1.85.223.76
     * @return
     */
    public static String getAddress(String ip) {
        try {
            DataBlock dataBlock = dbSearcher.memorySearch(ip);
            String region = dataBlock.getRegion();
            List<String> split = StrUtil.split(region, "|");
            StrJoiner of = StrJoiner.of("|");
            of.append(split.get(0));
            of.append(split.get(2));
            of.append(split.get(3));
            of.append(split.get(4));
            return of.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public static String getAddress(long ip) {
        try {
            DataBlock dataBlock = dbSearcher.memorySearch(ip);
            String region = dataBlock.getRegion();
            List<String> split = StrUtil.split(region, "|");
            return split.get(0) + "|" + split.get(2) + "|" + split.get(3) + "|" + split.get(4);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}